package com.ant.storage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ant.storage.common.PageRequest;
import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.*;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.DictionaryMapper;
import com.ant.storage.mapper.SupplierContractMapper;
import com.ant.storage.mapper.SupplierInformationMapper;
import com.ant.storage.mapper.SupplierPayListMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.*;
import com.ant.storage.utils.DingDingUtil;
import com.ant.storage.vo.SupplierDetailsVo;
import com.ant.storage.vo.SupplierPayListVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author melon
 * @since 2022-03-16
 */
@Service
public class SupplierInformationServiceImpl extends ServiceImpl<SupplierInformationMapper, SupplierInformation> implements ISupplierInformationService {

    @Resource
    DictionaryMapper dictionaryMapper;

    @Resource
    SupplierPayListMapper supplierPayListMapper;

    @Resource
    ISupplierPayListService supplierPayListService;

    @Autowired
    IMonthlySettlementService monthlySettlementService;

    @Autowired
    IMonthlySettlementLogService settlementLogService;

    @Resource
    private ISubscribeService subscribeService;

    @Resource
    private IPurchaseOrdersService purchaseOrdersService;

    @Resource
    private IPurchaserRecordService purchaserRecordService;

    @Autowired
    IPurchaserRecordService recordService;

    @Resource
    IPurchaserSubscribeService purchaserSubscribeService;


    @Autowired
    IPurchaserRecordImgService purchaserRecordImgService;

    @Resource
    SupplierContractMapper supplierContractMapper;
    @Autowired
    public ServletContext servletContext;

    /**
     * 获取供应商信息数据分页列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<SupplierInformation> queryAllByPage(SupplierInformationDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        QueryWrapper<SupplierInformation> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getSupplierName())) {
            wrapper.lambda().eq(SupplierInformation::getSupplierName, dto.getSupplierName());
        }
        if (StringUtils.isNotEmpty(dto.getSupplierLinkman())) {
            wrapper.lambda().eq(SupplierInformation::getSupplierLinkman, dto.getSupplierLinkman());
        }
        if (StringUtils.isNotEmpty(dto.getSupplierTel())) {
            wrapper.lambda().eq(SupplierInformation::getSupplierTel, dto.getSupplierTel());
        }
        if (StringUtils.isNotEmpty(dto.getSupplierType())) {
            wrapper.lambda().eq(SupplierInformation::getSupplierType, dto.getSupplierType());
        }
        if (CollectionUtils.isNotEmpty(dto.getCityId())) {
            wrapper.lambda().in(SupplierInformation::getCityId, dto.getCityId());
        } else {
            UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
            wrapper.lambda().in(SupplierInformation::getCityId, userInfo.getCityId());
        }

        wrapper.eq("is_show", 1);
        wrapper.orderByDesc("id");

        List<SupplierInformation> list = this.baseMapper.selectList(wrapper);
        list.stream().map(item -> {
            List<Dictionary> dictionaries = dictionaryMapper.selectList(new QueryWrapper<Dictionary>().eq("id",
                    item.getSupplierType()));
            item.setSupplierTypeText(dictionaries.size() == 0 ? "暂无分类" : dictionaries.get(0).getTypeName());
            List<SupplierContract> contractList = supplierContractMapper.selectList(new QueryWrapper<SupplierContract>()
                    .eq("supplier_id", item.getId())
                    .eq("contract_state", 1));
            item.setSupplierContract(contractList);
            return item;
        }).collect(Collectors.toList());
        PageInfo<SupplierInformation> info = new PageInfo<>(list);
        return info;
    }

    /**
     * 保存供应商新
     *
     * @param supplierInformation
     * @param bindingResult
     * @return
     */
    @Override
    public ResultVo addSupplierInformation(SupplierInformation supplierInformation, BindingResult bindingResult) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        if (bindingResult.hasErrors()) {
            throw new AntException(bindingResult.getFieldError().getDefaultMessage());
        } else {
            if (supplierInformation.getId() == null || supplierInformation.getId() == 0) {
                SupplierInformation selectOne =
                        this.baseMapper.selectOne(new QueryWrapper<SupplierInformation>()
                        .eq("supplier_name", supplierInformation.getSupplierName()));
                if(selectOne!=null){
                   throw new AntException(ResultCode.FAILURE.getResultCode(),"已存在");
                }
                supplierInformation.setCreationTime(new Date());
                supplierInformation.setCreatorBy(userInfo.getNameId().toString());
                this.baseMapper.insert(supplierInformation);
                return ResultVo.success("保存成功");
            } else {
                this.baseMapper.updateById(supplierInformation);
                return ResultVo.success("修改成功");
            }
        }

    }

    /**
     * 通过id查询供应商采购结算信息
     *
     * @param dto
     * @return
     */
    @Override
    public PageInfo<SupplierPayList> findPaymenList(SupplierInformationDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        List<SupplierPayList> supplierInformationList =
                supplierPayListMapper.selectList(new QueryWrapper<SupplierPayList>().eq("supplier_id", dto.getId()));
        PageInfo<SupplierPayList> info = new PageInfo<>(supplierInformationList);
        return info;
    }

    /**
     * 通过id查询供应商采购新
     *
     * @return
     */
    @Override
    public PageInfo<SupplierPayListVo> findPaymenLists(SupplierOrderDto dto) {
        PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
        List<SupplierPayListVo> supplierPayListVos = supplierPayListMapper.findSupplierPaymenById(dto);
        supplierPayListVos.stream().map(item -> {
            if (item.getBills() != "" && item.getBills() != null) {
                List<PurchaserRecordImg> imgs = purchaserRecordImgService.list(new QueryWrapper<PurchaserRecordImg>()
                        .in("id", Arrays.asList(item.getBills().split(","))));
                List<String> list = imgs.stream().map(img -> {
                    return img.getUrl();
                }).collect(Collectors.toList());
                item.setPic(list);
                return item;
            } else {
                return item;
            }
        }).collect(Collectors.toList());
        PageInfo<SupplierPayListVo> info = new PageInfo<>(supplierPayListVos);
        return info;
    }

    @Override
    public ResultVo updateImgUrl(ImgUrlDto dto) {
        if (dto.getOrderList().size() > 0) {
            List<Subscribe> subscribeList = dto.getSupplierPayListVos().stream().map(item -> {
                Subscribe subscribe = new Subscribe();
                subscribe.setId(item.getSid()); // 物品id 88 ，89，，89
                subscribe.setBills(dto.getImgId());// 20
                return subscribe;
            }).collect(Collectors.toList());
            subscribeService.updateBatchById(subscribeList);

            //修改物品图片路径
            List<PurchaseOrders> ordersList = dto.getOrderList().stream().map(item -> {
                PurchaseOrders orders = new PurchaseOrders();
                orders.setId(item.getId()); // 物品id
                orders.setImg(dto.getImgId());
                purchaseOrdersService.update(new UpdateWrapper<PurchaseOrders>()
                        .set("img", dto.getImgId()).eq("parent_id", item.getId()));
                return orders;
            }).collect(Collectors.toList());
            return ResultVo.success("更新成功");
        } else {
            throw new AntException(ResultCode.NOT_FOUND);
        }
    }

    /**
     * 月结钉钉申请
     *
     * @return
     */
    public String addDingDing(PurchaserRecordDto dto, List<String> str) throws Exception {
        FundsDto fundsDto = new FundsDto();
        fundsDto.setAccess_token(DingDingUtil.obtainToken());
        fundsDto.setOriginator_userid(dto.getUserId());
        fundsDto.setDeptId(dto.getDeptId());
        fundsDto.setApprover_userid(dto.getApproval());
        fundsDto.setCc_userId(dto.getNotify());
        fundsDto.setDate(new Date().toString());
        fundsDto.setUrgency(dto.getUrgency()); //紧急程度
        fundsDto.setAmount(dto.getConsumePrice().toString());
        fundsDto.setPicture(str);
        List<ReimbursementProjectDto> dataList = new ArrayList<>();
        ReimbursementProjectDto reimbursementProjectDto = new ReimbursementProjectDto();
        reimbursementProjectDto.setProjectName(dto.getRemarks());
        dataList.add(reimbursementProjectDto);
        fundsDto.setProjectDtoList(dataList);
        //mSytz3-7Qfag_4PFN0eNBQ03271669079297
        System.out.println("fundsDto" + JSONObject.toJSONString(fundsDto));
        String process_instance_id = DingDingUtil.OldReimbursement(fundsDto);
        System.out.println(process_instance_id);
        return process_instance_id;
    }


    /**
     * 财务通过供应商id查看供应商结算申请明细
     *
     * @param pageRequest
     * @param id
     * @return
     */
    @Override
    public ResultVo getMonthlySettlementById(PageRequest pageRequest, Integer id) {
        PurchaserRecord list = recordService.getOne(new QueryWrapper<PurchaserRecord>().eq("id", id));
        if (list != null) {
            // TODO 重新写不对
            list.setMonthlySettlementVos(this.baseMapper.getMonthlySettlementById(id));
            list.setMonthlySettlementLogs(settlementLogService.list(new QueryWrapper<MonthlySettlementLog>()
                    .eq("parent_id", id)));
            return ResultVo.success("查询采购", list);
        } else {
            return ResultVo.fail("数据不存在");
        }

    }


    /**
     * ResultVo
     *
     * @param dto
     * @return
     */
    @Override
    public List<SupplierPayList> findSupplierSettlementDetailsIds(SupplierInformationDto dto) {

        List<SupplierPayList> payList = supplierPayListService.list(new QueryWrapper<SupplierPayList>().eq(
                "supplier_id", dto.getId()));
        return payList;
    }

    @Override
    public List<SupplierDetailsVo> details(TimeDto dto) {
        return this.baseMapper.details(dto);
    }
}
